# -*- coding: utf-8 -*-
###################################################################################
#   
#    Copyright (C) 2019 RedTN 
# 
#此程序是自由软件：您可以根据自由软件基金会发布的GNU Affero通用公共许可证（许可证的第3版或（由您选择）任何更高版本）的条款重新分发和/或修改它。
#这个程序是分发的，希望它是有用的，但没有任何保证；甚至没有隐含的保证适销性或适合特定用途。有关详细信息，请参阅GNU Affero通用公共许可证。
#
#您应该已经收到GNU Affero通用公共许可证的副本以及此程序。如果没有，请参见<http://www.gnu.org/licenses/>。#
###################################################################################

import re
from odoo import _, api, models


class MailTemplate(models.Model):
    _inherit = 'mail.template'

    
    def generate_email(self, res_ids, fields=None):
        obj = self.with_context(mail_debrand=True)
        #return super(MailTemplate, obj).generate_email(res_ids, fields=fields)
        res = super(MailTemplate, obj).generate_email(res_ids, fields=fields)
        if isinstance(res_ids, int):
            res['subject'] = self._debrand_body(res['subject'])
            res['body'] = self._debrand_body(res['body'])
            res['body_html'] = self._debrand_body(res['body_html'])
            #res_ids = [res_ids]
        else:
            for id in res_ids:
                res[id]['subject'] = self._debrand_body(res[id]['subject'])
                res[id]['body'] = self._debrand_body(res[id]['body'])
                res[id]['body_html'] = self._debrand_body(res[id]['body_html'])
        return res
    
        
        
    @api.model
    def _debrand_body(self, body):
        using_word = _('using')

        new_name = self.env['ir.config_parameter'].sudo().get_param('redtn_hrms.new_name')

        # print(body)
        body=re.sub(
            'Odoo', new_name, body, flags=re.IGNORECASE,
        )
        return re.sub(
             'https://www.odoo.com','http://www.%s.com/' % new_name, body,flags=re.IGNORECASE,
        )

    # @api.model
    # def render_template(self, template_txt, model, res_ids,
    #                     post_process=False):
    #     res = super(MailTemplate, self).render_template(
    #         template_txt, model, res_ids, post_process=post_process,
    #     )
    #
    #     if self.env.context.get('mail_debrand'):
    #         if isinstance(res, str):
    #             res = self._debrand_body(res)
    #         else:
    #             for res_id, body in res.items():
    #                 res[res_id] = self._debrand_body(body)
    #     return res

